/**
 * File: ConnectionPool.cc
 * Created Time: 2024-12-30
 * Author: chugehehe (3321592850@qq.com)
 */


#include "ConnectionPool.h"

#include <mutex>
#include <condition_variable>

using std::cout;
using std::endl;
using std::mutex;
using std::unique_lock;
using std::condition_variable;

ConnectionPool::ConnectionPool(size_t maxConnSize, const string &host, const string &user, const string &password, const string &database)
: _maxConnSize(maxConnSize)
{
    for(size_t i = 0; i < maxConnSize; ++i)
    {
        _conns.emplace_back(std::make_shared<MySQLConnection>(host, user, password, database));
        _idleConns.emplace_back(_conns.back());
    }
    cout << "ConnectionPool::ConnectionPool() 连接池初始化成功" << endl;
}

shared_ptr<MySQLConnection> ConnectionPool::getConnection()
{
    unique_lock<mutex> lock(_mutex);
    _cond.wait(lock, [this]() { return !_idleConns.empty(); });
    auto conn = _idleConns.back();
    _idleConns.pop_back();
    cout << "ConnectionPool::getConnection() 获取连接成功" << endl;
    return conn;
}

void ConnectionPool::releaseConnection(shared_ptr<MySQLConnection> &conn)
{
    unique_lock<mutex> lock(_mutex);
    _idleConns.push_back(conn);
    _cond.notify_one();
    cout << "ConnectionPool::releaseConnection() 释放连接成功" << endl;
}